#!/usr/bin/env python3
"""
Beakerlib MCP Server

面向 beakerlib 软件的命令行操作，提供以下 MCP tools：

1. beakerlib_mem_avg - 获取进程的平均内存使用情况
   参数：process_name (str) - 进程名称
   返回：统一 JSON 结构

2. beakerlib_mem_peak - 获取进程的峰值内存使用情况
   参数：process_name (str) - 进程名称
   返回：统一 JSON 结构

3. beakerlib_test_watcher - 监控测试进程
   参数：process_name (str) - 进程名称
   返回：统一 JSON 结构

4. beakerlib_journalling - 处理测试日志记录
   参数：meta_file (str) - 元数据文件路径, journal_file (str) - 日志文件路径, xsl_file (str) - XSLT 文件路径（可选）
   返回：统一 JSON 结构

5. beakerlib_journal_compare - 比较两个日志文件
   参数：file1 (str) - 第一个日志文件路径, file2 (str) - 第二个日志文件路径
   返回：统一 JSON 结构

6. beakerlib_summarize - 生成测试摘要
   参数：summary_file (str) - 摘要文件路径
   返回：统一 JSON 结构

7. beakerlib_lsb_release - 获取系统发行版信息
   参数：option (str) - 选项参数（如 -v, -i, -d, -r, -c, -s, -a, -h）
   返回：统一 JSON 结构
"""

import subprocess
import json
from typing import Optional
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("Beakerlib MCP Server")

@mcp.tool()
def beakerlib_mem_avg(process_name: str, ctx: Context) -> dict:
    """获取进程的平均内存使用情况
    
    参数:
        process_name: 进程名称
        
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = f"beakerlib-rlMemAvg {process_name}"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def beakerlib_mem_peak(process_name: str, ctx: Context) -> dict:
    """获取进程的峰值内存使用情况
    
    参数:
        process_name: 进程名称
        
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = f"beakerlib-rlMemPeak {process_name}"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def beakerlib_test_watcher(process_name: str, ctx: Context) -> dict:
    """监控测试进程
    
    参数:
        process_name: 进程名称
        
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = f"beakerlib-testwatcher {process_name}"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def beakerlib_journalling(meta_file: str, journal_file: str, xsl_file: Optional[str] = None, ctx: Context) -> dict:
    """处理测试日志记录
    
    参数:
        meta_file: 元数据文件路径
        journal_file: 日志文件路径
        xsl_file: XSLT 文件路径（可选）
        
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    if xsl_file:
        command = f"beakerlib-journalling -m {meta_file} -j {journal_file} -x {xsl_file}"
    else:
        command = f"beakerlib-journalling -m {meta_file} -j {journal_file}"
    
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def beakerlib_journal_compare(file1: str, file2: str, ctx: Context) -> dict:
    """比较两个日志文件
    
    参数:
        file1: 第一个日志文件路径
        file2: 第二个日志文件路径
        
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = f"beakerlib-journalcmp {file1} {file2}"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def beakerlib_summarize(summary_file: str, ctx: Context) -> dict:
    """生成测试摘要
    
    参数:
        summary_file: 摘要文件路径
        
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = f"beakerlib-deja-summarize {summary_file}"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def beakerlib_lsb_release(option: str, ctx: Context) -> dict:
    """获取系统发行版信息
    
    参数:
        option: 选项参数（如 -v, -i, -d, -r, -c, -s, -a, -h）
        
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = f"beakerlib-lsb_release {option}"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()